// Problem: 
// Contest: 
// URL: 
// Memory Limit: 
// Time Limit: 
// #pragma GCC optimize("Ofast")
// #pragma GCC optimize("unroll-loops")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int read(){
	int s=0,w=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
	while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
	return s*w;
}
#include <iostream>
#include <iomanip>
using namespace std;

// 定义链表节点结构
struct PolyNode {
	double coef; // 系数
	int exp;     // 指数
	PolyNode* next;
	PolyNode(double c, int e) : coef(c), exp(e), next(nullptr) {}
};

// 创建多项式链表
PolyNode* createPoly() {
	int n;
	cout << "请输入多项式的项数: ";
	cin >> n;
	PolyNode* head = nullptr;
	PolyNode* tail = nullptr;
	
	for (int i = 0; i < n; ++i) {
		double coef;
		int exp;
		cout << "请输入第" << i + 1 << "项的系数和指数 (空格分隔): ";
		cin >> coef >> exp;
		PolyNode* newNode = new PolyNode(coef, exp);
		if (!head) {
			head = tail = newNode;
		} else {
			tail->next = newNode;
			tail = newNode;
		}
	}
	return head;
}

// 打印多项式
void printPoly(PolyNode* poly) {
	while (poly) {
		cout << fixed << setprecision(1) << poly->coef << " " << poly->exp;
		if (poly->next) cout << " ";
		poly = poly->next;
	}
	cout << endl;
}

// 多项式相加
PolyNode* addPoly(PolyNode* p1, PolyNode* p2) {
	PolyNode dummy(0, 0); // 哨兵节点
	PolyNode* tail = &dummy;
	
	while (p1 && p2) {
		if (p1->exp > p2->exp) {
			tail->next = new PolyNode(p1->coef, p1->exp);
			p1 = p1->next;
		} else if (p1->exp < p2->exp) {
			tail->next = new PolyNode(p2->coef, p2->exp);
			p2 = p2->next;
		} else {
			double sumCoef = p1->coef + p2->coef;
			if (sumCoef != 0) {
				tail->next = new PolyNode(sumCoef, p1->exp);
			}
			p1 = p1->next;
			p2 = p2->next;
		}
		if (tail->next) tail = tail->next;
	}
	
	// 处理剩余项
	while (p1) {
		tail->next = new PolyNode(p1->coef, p1->exp);
		p1 = p1->next;
		tail = tail->next;
	}
	while (p2) {
		tail->next = new PolyNode(p2->coef, p2->exp);
		p2 = p2->next;
		tail = tail->next;
	}
	
	return dummy.next;
}

signed main() {
	cout << "输入第一个多项式:" << endl;
	PolyNode* poly1 = createPoly();
	
	cout << "输入第二个多项式:" << endl;
	PolyNode* poly2 = createPoly();
	
	// 多项式相加
	PolyNode* result = addPoly(poly1, poly2);
	
	// 打印结果
	cout << "相加后的多项式为: ";
	printPoly(result);
	
	return 0;
}

